//
//  JoPrivatismViewController.m
//  RunningMan
//
//  Created by 姜勇利 on 16/5/19.
//  Copyright © 2016年 JohnnyB. All rights reserved.
//

#import "JoPrivatismViewController.h"
#import "Masonry.h"
#import "JoInfoView.h"
#import "JoUserViewController.h"
#import "JoPhotoViewController.h"
#import "JoCollectionViewController.h"
#import "JoStatisticsViewController.h"
#import "JoBackCollectionViewCell.h"
#import "EMSDk.h"
#import "JoLoginViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "APPTools.h"
#import <BmobSDK/Bmob.h>
#import "CoolVideoViewController.h"
#import "MapViewController.h"
#import "ViewControllerOfChatList.h"


@interface JoPrivatismViewController () <UICollectionViewDelegate, UICollectionViewDataSource, CLLocationManagerDelegate>

// 照片墙
@property (nonatomic, strong) UICollectionView *photosCollectionView;
// 城市名字
@property (nonatomic, copy) NSString *currentCity;
// 定位管理者
@property (nonatomic, strong) CLLocationManager *locMgr;
//
@property (nonatomic, strong) JoInfoView *infoView;

@property (nonatomic, strong) NSString *name;

@end

@implementation JoPrivatismViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatSubViews];
    [self locateCurrentCity];
}

#pragma mark -
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSUserDefaults *userDeaults = [NSUserDefaults standardUserDefaults];
    BmobQuery *query = [BmobQuery queryWithClassName:@"userInfo"];
    [query whereKey:@"userName" equalTo:[EMClient sharedClient].currentUsername];
    [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        for (BmobObject *obj in array) {
            self.infoView.nameLabel.text = [obj objectForKey:@"name"];
        }
    }];
    
    if ([userDeaults dataForKey:[EMClient sharedClient].currentUsername]) {
        [self.infoView.userImage setImage:[UIImage imageWithData:[userDeaults dataForKey:[EMClient sharedClient].currentUsername]]];
    }
    else
    {
        self.infoView.userImage.image = [UIImage imageNamed:@"1401835_shi04.jpg"];
    }
    self.navigationController.navigationBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 创建子控件
- (void)creatSubViews
{
// 照片墙
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height);
    self.photosCollectionView = [[UICollectionView alloc]initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    [self.view addSubview:self.photosCollectionView];
    self.photosCollectionView.delegate = self;
    self.photosCollectionView.dataSource = self;
    [self.photosCollectionView registerClass:[JoBackCollectionViewCell class] forCellWithReuseIdentifier:@"photoPool"];
    self.photosCollectionView.pagingEnabled = YES;
    self.photosCollectionView.backgroundColor = [UIColor whiteColor];
    self.photosCollectionView.bounces = NO;
    
    self.infoView = [[JoInfoView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height / 2.f, self.view.frame.size.width, self.view.frame.size.height / 2.f)];
    [self.view addSubview:self.infoView];
    [self.view bringSubviewToFront:self.infoView];
// 调用block跳转下一界面
    __weak typeof(self)weakself = self;
    self.infoView.pushNextPage = ^(UIButton *button)
    {
        if (button.tag == 100) {
            JoUserViewController *userViewController = [[JoUserViewController alloc]init];
            userViewController.area = weakself.infoView.cityLabel.text;
            [weakself.navigationController pushViewController:userViewController animated:YES];
        }
        if (button.tag == 200) {
            JoPhotoViewController *photoViewController = [[JoPhotoViewController alloc]init];
            [weakself.navigationController pushViewController:photoViewController animated:YES];
        }
        if (button.tag == 300) {
            JoCollectionViewController *collectionViewController = [[JoCollectionViewController alloc]init];
            [weakself.navigationController pushViewController:collectionViewController animated:YES];
        }
        if (button.tag == 400) {
            JoStatisticsViewController *statisticsViewController = [[JoStatisticsViewController alloc]init];
            [weakself.navigationController pushViewController:statisticsViewController animated:YES];
        }
    };
    
 // 定时器定时刷新天气预报
    [NSTimer scheduledTimerWithTimeInterval:3600.f target:self selector:@selector(getWeather) userInfo:nil repeats:YES];
    
 // 返回按钮
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:cancelButton];
    [self.view bringSubviewToFront:cancelButton];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(20);
        make.left.equalTo(self.view).with.offset(15);
        make.width.height.mas_equalTo(45);
    }];
    [cancelButton setImage:[UIImage imageNamed:@"8"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(handleCancelPage:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)handleCancelPage:(UIButton *)button
{
    if (self.navigationController.viewControllers.count > 1) {
         NSLog(@"pop");
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else
    {
        NSLog(@"push");
        CoolVideoViewController *coolVideo = [[CoolVideoViewController alloc]init];
//        if (self.tabBarController == nil) {
//            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//            UITabBarController *newTabBarController = [storyBoard instantiateViewControllerWithIdentifier:@"UITabBarController"];
//            MapViewController *map = [[MapViewController alloc]init];
//            ViewControllerOfChatList *chat = [[ViewControllerOfChatList alloc]init];
//            newTabBarController.viewControllers = @[coolVideo, map, chat];
//        }
       [self.navigationController pushViewController:coolVideo animated:YES];
    }
}

#pragma mark - collectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JoBackCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"photoPool" forIndexPath:indexPath];
    if (indexPath.item == 0) {
        cell.backImage.image = [UIImage imageNamed:@"ZRuT.jpeg"];
    }
    if (indexPath.item == 1) {
        cell.backImage.image = [UIImage imageNamed:@"c1e2511.jpg"];
    }
    if (indexPath.item == 2) {
        cell.backImage.image = [UIImage imageNamed:@"CaESv.png"];
    }
    if (indexPath.item == 3) {
        cell.backImage.image = [UIImage imageNamed:@"GsWnH.jpeg"];
    }
    if (indexPath.item == 4) {
        cell.backImage.image = [UIImage imageNamed:@"JBmQ3.jpeg"];
    }
    return cell;
}

#pragma mark - button点击事件
- (void)handleCancel:(UIButton *)button
{
    EMError *error = [[EMClient sharedClient] logout:YES];
    if (!error) {
        NSLog(@"退出成功");
        JoLoginViewController *loginPage = [[JoLoginViewController alloc]init];
        [self presentViewController:loginPage animated:YES completion:^{
            
        }];
    }
}

#pragma mark - 城市定位
// 城市定位
- (void)locateCurrentCity
{
    // 判断用户定位是否开启
    if ([CLLocationManager locationServicesEnabled]) {
        self.locMgr = [[CLLocationManager alloc]init];
        [_locMgr requestWhenInUseAuthorization];
        self.locMgr.delegate = self;
        
        // 开始定位用户的位置
        
        // 每隔多少米定位一次（这里的设置为任何移动）
        //  self.locMgr.distanceFilter = kCLDistanceFilterNone;
        // 设置定位精确度
        self.locMgr.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        _locMgr.distanceFilter = kCLDistanceFilterNone;
        [self.locMgr startUpdatingLocation];
        NSLog(@"开始定位开启");
    }
    else
    {
        NSLog(@"定位服务失败");
    }
}

// 当用户定位到位置时，调用此方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    // 数组里装的是CLLocationManager，一个CLLocationManager代表一个位置
    CLLocation *loc = [locations lastObject];
    
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    [geoCoder reverseGeocodeLocation:loc completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            NSString *cityName = placeMark.locality;
            NSString *areaName = placeMark.subLocality;
            if (!self.currentCity) {
                self.currentCity = NSLocalizedString(@"home_cannot_locate_city", comment:@"无法定位当前城市");
            }
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.currentCity = [cityName stringByAppendingString:areaName];
                    NSLog(@"%@", self.currentCity);
                    self.infoView.cityLabel.text = self.currentCity;
                    [self getWeather];
                });
            });
        }
        else if (error == nil && placemarks.count == 0)
        {
            NSLog(@"No location and error returned");
        }
        else if (error)
        {
            NSLog(@"Location error:%@", error);
        }
        
    }];
    // 如果定位服务不需要实时更新的话，需要停止位置的更新
    [self.locMgr stopUpdatingLocation];
}
// 定位失败时激发的方法
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    NSLog(@"定位失败: %@",error);
}

#pragma mark - 天气预报
- (void)getWeather
{
    NSString *city = [self.infoView.cityLabel.text substringToIndex:2];
    NSLog(@"%@", city);
    [APPTools GETWithURL:[NSString stringWithFormat:@"https://api.thinkpage.cn/v3/weather/now.json?key=du13foget0a3vdev&location=%@&language=zh-Hans&unit=c", city] par:nil success:^(id responseObject) {
        
        NSString *textString = responseObject[@"results"][0][@"now"][@"text"];
        NSLog(@"%@", textString);
        NSString *codeString = responseObject[@"results"][0][@"now"][@"code"];
        NSString *temperatureString = responseObject[@"results"][0][@"now"][@"temperature"];
        
        NSString *stringText = @"天气  ";
        NSString *str1 = [stringText stringByAppendingString:textString];
        
        NSString *stringTemperature = @"  气温  ";
        NSString *str2 = [stringTemperature stringByAppendingString:temperatureString];
        NSString *str4 = [str2 stringByAppendingString:@"℃"];
        
        NSString *str3 = [str1 stringByAppendingString:str4];
        
        self.infoView.weaLabel.text = str3;
        
        self.infoView.imageWeather.image = [UIImage imageNamed:[NSString stringWithFormat:@"T%@", codeString]];
        
    } filed:^(NSError *error) {
        
        NSLog(@"获取天气失败");
        
    }];
    
}

#pragma mark - 
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}



#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
